import { Injectable } from "@nestjs/common";
import { CreatePermissionDto } from "./dto/create-permission.dto";
import { UpdatePermissionDto } from "./dto/update-permission.dto";
import { ObjectId } from "mongodb";
import { Core } from "src/core";

@Injectable()
export class PermissionService {
    create(createPermissionDto: CreatePermissionDto) {
        return this.getCollection().insertOne({
            ...createPermissionDto,
            createdAt: new Date(),
            updatedAt: new Date()
        });
    }

    async findAll() {
        const ary = await this.getCollection().find({}).toArray();
        return ary;
    }

    async findOne(id: string) {
        const ary = await this.getCollection().findOne({ _id: new ObjectId(id) });
        return ary;
    }

    async update(id: string, updatePermissionDto: UpdatePermissionDto) {
        const filter = { _id: new ObjectId(id) };
        const update = { $set: { ...updatePermissionDto, updatedAt: new Date() } };
        const result = await this.getCollection().updateOne(filter, update);
        return `Updated ${result.modifiedCount} document(s)`;
    }

    async remove(id: string) {
        const insertResult = await this.getCollection().deleteOne({ _id: new ObjectId(id) });
        return insertResult.deletedCount.toString();
    }

    getCollection() {
        return Core.ins.db.collection("permission");
    }
}
